package com.mrroman.linksender.gui;

import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.TrayIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JDialog;

import com.mrroman.linksender.gui.actions.SendMessageDialogAction;
import com.mrroman.linksender.gui.actions.ShowChatDialogAction;
import com.mrroman.linksender.ioc.In;
import com.mrroman.linksender.ioc.Init;
import com.mrroman.linksender.ioc.Name;

@Name("gui.MyTrayIcon")
public class MyTrayIcon extends TrayIcon {

    private final static Image icon;
    @In
    private ShowChatDialogAction showChatDialogAction;
    @In
    private TrayPopupMenu trayPopupMenu;
    private TrickyDialog trickyDialog;

    static {
        try {
            icon = ImageIO.read(MyTrayIcon.class.getResourceAsStream("resources/icon.png"));
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
        }
    }

    public MyTrayIcon() {
        super(icon);
    }

    @Init
    public void initPopupMenu() {
        trickyDialog = new TrickyDialog();

        addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1) {
                    showChatDialogAction.actionPerformed(null);
                }
                if (e.getButton() == MouseEvent.BUTTON3) {
                    Rectangle rect = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
                    int y;

                    if (e.getYOnScreen() < rect.y) {
                        y = e.getYOnScreen();
                    } else {
                        y = e.getYOnScreen() - (int) trayPopupMenu.getPreferredSize().getHeight();
                    }

                    trickyDialog.setVisible(true);
                    trayPopupMenu.show(trickyDialog, e.getXOnScreen(), y);
                }
            }
        });

        trickyDialog.addWindowFocusListener(new WindowFocusListener() {

            @Override
            public void windowGainedFocus(WindowEvent e) {
                // TODO Auto-generated method stub
            }

            @Override
            public void windowLostFocus(WindowEvent e) {
                trayPopupMenu.setVisible(false);
                trickyDialog.setVisible(false);
            }
        });

    }

    private class TrickyDialog extends JDialog {

        public TrickyDialog() {
            setFocusable(false);
            setUndecorated(true);
            setBounds(0, 0, 0, 0);
        }
    }
}
